import { createStore } from 'vuex'
import { login, getinfo, logout } from '@/api/manager'
import { setToken, removeToken } from '@/composables/auth'

const store = createStore({
  state() {
    return {
      user: {},
      asideWidth: '250px',
      menus: [],
      ruleNames: [],
    }
  },
  mutations: {
    SET_USERINFO(state, user) {
      state.user = user
    },
    SET_ASIDEWIDTH(state) {
      state.asideWidth = state.asideWidth == '250px' ? '64px' : '250px'
    },
    SET_MENUS(state, data) {
      state.menus = data
    },
    SET_RULENAMES(state, data) {
      state.ruleNames = data
    },
  },
  actions: {
    login({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data)
          .then((res) => {
            setToken(res.data.token)
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    },
    getinfo({ commit }) {
      return new Promise((resolve, reject) => {
        getinfo()
          .then((res) => {
            commit('SET_USERINFO', res.data)
            commit('SET_MENUS', res.data.menus)
            commit('SET_RULENAMES', res.data.ruleNames)
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    },

    logout({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then((res) => {
            commit('SET_USERINFO', {})
            removeToken()
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    },
  },
})

export default store
